package com.icesoft.xsnow.framework.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.icesoft.xsnow.common.core.constant.PageConstants;
import com.icesoft.xsnow.common.core.constant.enums.IErrorCode;
import com.icesoft.xsnow.framework.api.reponses.R;
import com.icesoft.xsnow.framework.api.util.AntiSQLFilter;
import com.icesoft.xsnow.framework.api.util.TypeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: xsnow
 * @description: 顶层Controller
 * @author: xuefeng.gao
 * @create: 2019-05-15 16:13
 **/
public abstract class BaseController {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    /**
     * 成功返回
     *
     * @param object
     * @return
     */
    public <T> R<T> success(T object) {
        return R.<T>success(response, object);
    }

    /**
     * 成功返回
     *
     * @return
     */
    public R<Void> success() {
        return success(HttpStatus.OK);
    }

    /**
     * 成功返回
     *
     * @param status
     * @param object
     * @return
     */
    public <T> R<T> success(HttpStatus status, T object) {
        return R.<T>success(response, status, object);
    }

    /**
     * 成功返回
     *
     * @param status
     * @return
     */
    public R<Void> success(HttpStatus status) {
        return R.<Void>success(response, status);
    }


    public R<Void> fail(IErrorCode errorCode,Exception ex){
        return R.failure(errorCode.convert(),ex);
    }



    /**
     * 获取分页对象
     *
     * @return
     */
    protected <T> Page<T> getPage() {
        return getPage(false);
    }

    /**
     * 获取分页对象
     *
     * @param openSort
     * @return
     */
    protected <T> Page<T> getPage(boolean openSort) {
        int index = 1;
        // 页数
        Integer cursor = TypeUtils.castToInt(request.getParameter(PageConstants.PAGE_PAGE), index);
        // 分页大小
        Integer limit = TypeUtils.castToInt(request.getParameter(PageConstants.PAGE_ROWS), PageConstants.DEFAULT_LIMIT);
        // 是否查询分页
        Boolean searchCount = TypeUtils.castToBoolean(request.getParameter(PageConstants.SEARCH_COUNT), true);
        limit = limit > PageConstants.MAX_LIMIT ? PageConstants.MAX_LIMIT : limit;
        Page<T> page = new Page<T>(cursor, limit, searchCount);
        if (openSort) {
            page.setAsc(getParameterSafeValues(PageConstants.PAGE_ASCS));
            page.setDesc(getParameterSafeValues(PageConstants.PAGE_DESCS));
        }
        return page;
    }



    /**
     * 获取安全参数(SQL ORDER BY 过滤)
     *
     * @param parameter
     * @return
     */
    protected String[] getParameterSafeValues(String parameter) {
        return AntiSQLFilter.getSafeValues(request.getParameterValues(parameter));
    }

}
